from flask import Blueprint, render_template, request, abort
import pymongo, math

from ..database import db


blog = Blueprint("blog", __name__)


@blog.route("/", methods=["GET"])
def index():
    page = request.args.get("page", type=int, default=1)
    articles = db.article.find().sort("id", pymongo.DESCENDING).skip((page - 1) * 10).limit(10)
    return render_template("blog/index.html", db=db, articles=articles, page=page, tot_page=math.ceil(db.article.find().count() / 10))


@blog.route("/archive/", methods=["GET"])
def archive():
    page = request.args.get("page", type=int, default=1)
    articles = db.article.find().sort("id", pymongo.DESCENDING).skip((page - 1) * 20).limit(20)
    return render_template("blog/archive.html", db=db, articles=articles, page=page, tot_page=math.ceil(db.article.find().count() / 20))


@blog.route("/article/<int:article_id>/", methods=["GET"])
def article(article_id):
    article = db.article.find_one({"id": article_id})
    if not article:
        return abort(404)
    return render_template("blog/article.html", db=db, article=article)


@blog.route("/category/<category_name>/", methods=["GET"])
def category(category_name):
    category = db.category.find_one({"name": category_name})
    if not category:
        abort(404)
    page = request.args.get("page", type=int, default=1)
    articles = db.article.find({"category": category_name}).sort("id", pymongo.DESCENDING).skip((page - 1) * 10).limit(10)
    return render_template("blog/category.html", db=db, category=category, articles=articles, page=page, tot_page=math.ceil(db.article.find({"category": category_name}).count() / 10))


@blog.route("/tag/", methods=["GET"])
def tags():
    return render_template("blog/tags.html", db=db, tags=db.tag.find().sort("count", pymongo.DESCENDING))


@blog.route("/tag/<tag_name>/", methods=["GET"])
def tag_show(tag_name):
    tag = db.tag.find_one({"name": tag_name})
    if not tag:
        abort(404)
    page = request.args.get("page", type=int, default=1)
    articles = db.article.find({"tag": tag_name}).sort("id", pymongo.DESCENDING).skip((page - 1) * 10).limit(10)
    return render_template("blog/tag_show.html", db=db, tag=tag, articles=articles, page=page, tot_page=math.ceil(db.article.find({"tag": tag_name}).count() / 10))


@blog.route("/page/<page_name>/", methods=["GET"])
def page(page_name):
    page = db.page.find_one({"name": page_name})
    if not page:
        return abort(404)
    return render_template("blog/page.html", db=db, page=page)